package top.oylan.manager.controller.admin;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import top.oylan.manager.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by A on 2019/2/2.
 */
@Controller
@RequestMapping("/admin")
public class AdminAuthController {

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){

        return "admin/login";
    }

    @RequestMapping(value = "/sign",method = RequestMethod.POST)
    public String sign(HttpServletRequest request,
                       @RequestParam(value = "username")String username,
                       @RequestParam(value = "password")String password){

        // 当前对象
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        if(!subject.isAuthenticated()){
            try {
                subject.login(token);
            }catch (LockedAccountException e){
                // 账号被禁用
                request.setAttribute("error_message","账号被禁用");
                return "admin/login";
            }catch (DisabledAccountException e){
                // 不是管理员
                request.setAttribute("error_message","不是管理员");
                return "admin/login";
            }
            catch (IncorrectCredentialsException e){
                // 密码错误
                request.setAttribute("error_message","密码错误");
                return "admin/login";
            }catch (UnknownAccountException e){
                // 账号不存在
                request.setAttribute("error_message","账号不存在");
                return "admin/login";
            }catch (AuthenticationException e){
                // 登录失败
                request.setAttribute("error_message","登录失败");
                return "admin/login";
            }
        }
        return "redirect:/admin";
    }
}
